// pages/venue/timeslot.js
const api = require('../../utils/api');
const priceCalculator = require('../../utils/price_calculator.js');

Page({
  data: {
    venueId: null,
    venueInfo: {},
    roomName: '',
    loading: false,
    keyword: '',
    selectedDate: '',
    selectedPackage: 0,
    selectedStartTime: '',
    selectedEndTime: '',
    totalPrice:0,
    hourlyPrice: 0, // 每小时续单价格
    originalPrice: 0, // 原价
    discountAmount: 0, // 优惠金额
    orderHour:0,//订单时长
    timeSlots: [], // 存储24小时时间段数据
    showConfirmModal: false, // 控制预定确认弹窗显示
    dateList: [], // 存储日期列表数据
    packagePrices: {}, // 存储各套餐的价格数据
    packageList: [], // 存储套餐列表数据

    // 添加优惠券和团购券相关数据
    groupBuyId: null, // 选择的团购券ID
    couponId: null, // 选择的优惠券ID
    selectedGroupBuy: null, // 选择的团购券详情
    selectedCoupon: null, // 选择的优惠券详情

    // 添加账户余额相关数据
    accountInfo: null, // 账户信息
    useBalance: false, // 是否使用余额支付
    balancePayAmount: 0, // 使用余额支付的金额
    remainingPayAmount: 0, // 剩余需要支付的金额

    // 时间选择器相关数据
    showTimePickerModal: false, // 控制时间选择模态框显示
    isSelectingStartTime: true, // 标记是否正在选择开始时间
    timePickerDateList: [], // 日期选项，从当天开始到后5天
    timePickerHourList: [], // 小时选项，从当前整点开始到23点
    timePickerMinuteList: ['00', '05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55'], // 分钟选项
    selectedTimePickerDate: '', // 选中的日期
    selectedTimePickerHour: '', // 选中的小时
    selectedTimePickerMinute: '00', // 选中的分钟
    
    // 续单相关数据
    isRenew: false, // 是否为续单模式
    originalBookingId: null, // 原订单ID
    originalBookingInfo: null, // 原订单信息
    preOrderId: null, // 预订单ID

    // 新增优惠券相关数据
    availableCoupons: [], // 可用优惠券列表
    hasCoupons: false, // 是否有可用优惠券
    showCouponModal: false, // 控制优惠券选择模态框显示
    timeBasedPricing: [], // 分时段定价
  },

  onLoad:async function (options) {
    // 检查是否是续单操作
    if (options.isRenew === 'true' && options.originalBookingId) {
      this.setData({
        isRenew: true,
        originalBookingId: options.originalBookingId
      });
      // 加载原订单信息
      this.loadOriginalBookingInfo(options.originalBookingId);
    }
    // 获取传入的场馆ID和房间名称
    if (options.venueId || options.roomId) {
      // 将场地ID和名称保存到本地存储
      const storeId = options.venueId;
      const roomId =  options.roomId;
      wx.setStorageSync('venue_id', roomId);
      wx.setStorageSync('room_name', options.roomName || '');
      
      this.setData({
        venueId: roomId,
        roomName: options.roomName || ''
      });
      
      // 加载场馆信息
      await this.loadVenueInfo(roomId);
    } else {
      // 尝试从本地存储获取场地ID和名称
      const venueId = wx.getStorageSync('venue_id');
      const roomName = wx.getStorageSync('room_name');
      
      if (venueId) {
        this.setData({
          venueId: venueId,
          roomName: roomName
        });
        
        // 使用本地存储的场地ID加载场馆信息
       await  this.loadVenueInfo(venueId);
      } else {
        wx.showToast({
          title: '未找到场地信息',
          icon: 'none'
        });
        
        // 返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
        return;
      }
    }
    
    // 生成日期列表
    this.generateDateList();

    // 生成时间段数据
    this.generateTimeSlots();

    // 生成时间选择器选项
    this.generateTimePickerOptions();

    // 获取套餐数据
    this.loadPackageData();
    
    // 获取账户信息
    this.loadAccountInfo();

    // 设置默认时间
    this.setDefaultTime();
    // 检查是否传入了团购券ID或优惠券ID
    if (options.groupbuy_id) {
      this.setData({ groupBuyId: options.groupbuy_id });
      this.loadGroupBuyDetail(options.groupbuy_id);
    }

    if (options.coupon_id) {
      this.setData({ couponId: options.coupon_id });
      this.loadCouponDetail(options.coupon_id);
    }
    
    this.recalculatePrice();
  },

  // 设置默认时间
  setDefaultTime: function() {
    let startTime;
    let hours, minutes;

    const formatTime = (h, m) => {
      return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
    }
    console.log("this.data.selectedStartTime:",this.data.selectedStartTime)
    if (this.data.selectedStartTime) {
      startTime = this.data.selectedStartTime;
      [hours, minutes] = startTime.split(':').map(Number);
    } else {
      const now = new Date();
      hours = now.getHours();
      minutes = now.getMinutes();

      // 将分钟向上取整到最近的5分钟
      minutes = Math.ceil(minutes / 5) * 5;
      if (minutes >= 60) {
        minutes = 0;
        hours += 1;
      }

      if (hours >= 24) {
        hours = 0; // 如果超过24点，则从0点开始
      }
      startTime = formatTime(hours, minutes);
    }

    let endHours = hours + 4;
    if (endHours >= 24) {
      endHours = endHours % 24;
    }
    const endTime = formatTime(endHours, minutes);

    this.setData({
      selectedStartTime: startTime,
      selectedEndTime: endTime,
    });
    
  },

  // 加载原订单信息
  loadOriginalBookingInfo: function(bookingId) {
    wx.showLoading({ title: '加载中...' });
    
    api.order.getBookingDetail(bookingId)
      .then(res => {
        if (res && res.success && res.data) {
          const bookingInfo = res.data;
          
          // 存储原订单信息
          this.setData({ 
            originalBookingInfo: bookingInfo,
            roomName: bookingInfo.venue_name || this.data.roomName
          });
          
          // 弹窗提示续单
          wx.showToast({
            title: '请选择新的时间段',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error('获取原订单信息失败:', err);
        wx.showToast({
          title: '加载原订单信息失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 加载团购券详情
  loadGroupBuyDetail: function (groupBuyId) {
    if (parseInt(this.data.selectedPackage) >0) {
      wx.showToast({
        title: '已选择套餐，无法使用团购券',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({ title: '加载中...' });

    api.groupBuy.getMyGroupBuy({ id: groupBuyId })
      .then(res => {
        if (res && res.success && res.data && res.data.length > 0) {
          // 找到对应ID的团购券
          const groupBuy = res.data.find(item => item.id == groupBuyId) || res.data[0];

          // 校验团购券可用性
          if (!this.isItemAvailable(groupBuy, this.data.selectedDate, this.data.selectedStartTime, this.data.selectedEndTime)) {
            wx.showToast({
              title: '当前时间段不适用该团购券',
              icon: 'none'
            });
            return; // 校验不通过则不继续
          }

          this.setData({
            selectedGroupBuy: groupBuy
          });
          // 更新总价
          this.calculateTotalPrice();

          wx.showToast({
            title: '已选择团购券',
            icon: 'success'
          });
        }
      })
      .catch(err => {
        console.error('获取团购券详情失败:', err);
        wx.showToast({
          title: '获取团购券失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 加载优惠券详情
  loadCouponDetail: function (couponId) {
    if (parseInt(this.data.selectedPackage) >0) {
      wx.showToast({
        title: '已选择套餐，无法使用优惠券',
        icon: 'none'
      });
      return;
    }
    wx.showLoading({ title: '加载中...' });

    api.coupon.getMyCoupons()
      .then(res => {
        if (res && res.success && res.data) {
          // 找到对应ID的优惠券
          const coupon = res.data.find(item => item.id == couponId);

          if (coupon) {
            // 校验优惠券可用性
            if (!this.isItemAvailable(coupon, this.data.selectedDate, this.data.selectedStartTime, this.data.selectedEndTime)) {
              wx.showToast({
                title: '当前时间段不适用该优惠券',
                icon: 'none'
              });
              return; // 校验不通过则不继续
            }

            this.setData({
              selectedCoupon: coupon
            });

            // 更新总价
            this.calculateTotalPrice();

            wx.showToast({
              title: '已选择优惠券',
              icon: 'success'
            });
          }
        }
      })
      .catch(err => {
        console.error('获取优惠券详情失败:', err);
        wx.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 通用校验函数
  isItemAvailable: function(item, selectedDate, startTime, endTime) {
    const dateParts = selectedDate.split('.');
    const year = new Date().getFullYear();
    const month = parseInt(dateParts[0], 10) - 1;
    const day = parseInt(dateParts[1], 10);
    const checkDate = new Date(year, month, day);
    const currentDay = checkDate.getDay(); // 0-6, 0是周日

    const [startHour, startMinute] = startTime.split(':').map(Number);
    const selectedStartTimeInMinutes = startHour * 60 + startMinute;

    const [endHour, endMinute] = endTime.split(':').map(Number);
    const selectedEndTimeInMinutes = endHour * 60 + endMinute;
    console.log(item,selectedDate,startTime,endTime)
    // 1. 校验可用星期
    let availableDaysOfWeek = [];
    try {
      if (item.available_weekdays) {
        availableDaysOfWeek = JSON.parse(item.available_weekdays);
      }
    } catch (e) {
      console.error('Error parsing available_weekdays:', e);
    }
    if (availableDaysOfWeek.length > 0) {
      const availableDays = availableDaysOfWeek.map(d => d === 0 ? 7 : d); // 将周日0转为7
      const currentDayOfWeek = currentDay === 0 ? 7 : currentDay; // 将当前周日0转为7
      console.log(currentDayOfWeek,availableDays)
      if (!availableDays.includes(currentDayOfWeek)&&!availableDays.includes(0)) {
        console.log("星期验证不通过：",availableDays.includes(currentDayOfWeek),availableDays.includes(0))
        return false;
      }
    }

    // 2. 校验可用时段
    let availableTimeRanges = [];
    try {
      if (item.available_times) {
        availableTimeRanges = JSON.parse(item.available_times);
      }
    } catch (e) {
      console.error('Error parsing available_times:', e);
    }
    if (availableTimeRanges.length > 0) {
      const isInAvailableTime = availableTimeRanges.some(range => {
        const startTimeStr = range.start_time || range.start;
        const endTimeStr = range.end_time || range.end;
        console.log(startTimeStr,endTimeStr)
        if (!startTimeStr || !endTimeStr) return false;

        const [rangeStartHour, rangeStartMinute] = startTimeStr.split(':').map(Number);
        const [rangeEndHour, rangeEndMinute] = endTimeStr.split(':').map(Number);
        const rangeStartTimeInMinutes = rangeStartHour * 60 + rangeStartMinute;
        const rangeEndTimeInMinutes = rangeEndHour * 60 + rangeEndMinute;
        // 检查预订时间段是否完全在可用时间段内
        return selectedStartTimeInMinutes >= rangeStartTimeInMinutes && selectedEndTimeInMinutes <= rangeEndTimeInMinutes;
      });
      console.log("isInAvailableTime:",isInAvailableTime)
      if (!isInAvailableTime) {
        return false;
      }
    }

    // 3. 校验可用门店
    let availableStoreIds = [];
    try {
      if (item.applicable_stores) {
        availableStoreIds = JSON.parse(item.applicable_stores);
      }
    } catch (e) {
      console.error('Error parsing applicable_stores:', e);
    }
    if (availableStoreIds.length > 0) {
      const storeId = this.data.venueInfo.store_id;
      if (!availableStoreIds.includes(storeId)) {
        return false;
      }
    }

    // 4. 校验可用场地
    let availableVenueIds = [];
    try {
      if (item.applicable_venues) {
        availableVenueIds = JSON.parse(item.applicable_venues);
      }
    } catch (e) {
      console.error('Error parsing applicable_venues:', e);
    }
    if (availableVenueIds.length > 0) {
      if (!availableVenueIds.includes(this.data.venueId)) {
        return false;
      }
    }

    return true;
  },

  // 生成日期列表数据
  generateDateList: function () {
    // 获取当前日期
    const now = new Date();
    const dateList = [];

    // 生成从当天开始的5天日期
    for (let i = 0; i < 5; i++) {
      const date = new Date(now);
      date.setDate(now.getDate() + i);

      // 格式化日期为MM.DD格式
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const formattedDate = month + '.' + day;

      // 获取星期几
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const weekday = weekdays[date.getDay()];

      dateList.push({
        date: formattedDate,
        day: weekday,
        isToday: i === 0 // 标记当天
      });
    }

    this.setData({
      dateList: dateList,
      selectedDate: dateList[0].date // 默认选中当天
    });
  },

  // 生成时间段数据
  generateTimeSlots: function (isToday = true) {
    // 获取当前时间
    const now = new Date();
    // 如果是今天，从当前小时开始；否则从0点开始
    const startHour = isToday ? now.getHours() : 0;

    let timeSlots = [];

    // 生成24小时的时间段
    for (let i = 0; i < 24; i++) {
      const hour = (startHour + i) % 24;
      // 仅当是“今天”的视图时，才需要判断是否跨天
      const isNextDay = isToday && (startHour + i >= 24);
      
      timeSlots.push({
        hour: hour,
        displayHour: isNextDay ? (hour === 0 ? '次日' : `${hour}`) : `${hour}`,
        status: 'available', // 默认可用，将在loadTimeSlotsData中更新
        isNextDay: isNextDay
      });
    }

    this.setData({
      timeSlots: timeSlots
    }, () => {
      // setData是异步的，在回调中加载数据以确保timeSlots已更新
      this.loadTimeSlotsData();
    });
  },

  // 根据选择的日期加载时间段状态数据
  loadTimeSlotsData: function () {
    const selectedDateObj = this.data.dateList.find(item => item.date === this.data.selectedDate);
    if (!selectedDateObj) return;

    wx.showLoading({ title: '加载中...' });

    const year = new Date().getFullYear();
    const [month, day] = this.data.selectedDate.split('.');
    const todayStr = `${year}-${month}-${day}`;

    // 计算次日日期
    const tomorrow = new Date(year, month - 1, day);
    tomorrow.setDate(tomorrow.getDate() + 1);
    const tomorrowYear = tomorrow.getFullYear();
    const tomorrowMonth = String(tomorrow.getMonth() + 1).padStart(2, '0');
    const tomorrowDay = String(tomorrow.getDate()).padStart(2, '0');
    const tomorrowStr = `${tomorrowYear}-${tomorrowMonth}-${tomorrowDay}`;

    const todayPromise = api.venue.getVenueTimeSlots(this.data.venueId, todayStr)
      .then(res => (res.success && res.data && res.data.time_slots) ? res.data.time_slots : [])
      .catch(err => {
        console.error(`获取${todayStr}时间段失败:`, err);
        return []; // 返回空数组以保证Promise.all成功
      });

    const tomorrowPromise = api.venue.getVenueTimeSlots(this.data.venueId, tomorrowStr)
      .then(res => (res.success && res.data && res.data.time_slots) ? res.data.time_slots : [])
      .catch(err => {
        console.error(`获取${tomorrowStr}时间段失败:`, err);
        return []; // 返回空数组
      });

    Promise.all([todayPromise, tomorrowPromise])
      .then(([todaySlots, tomorrowSlots]) => {
        this.updateViewWithTimeSlots(todaySlots, tomorrowSlots);
      })
      .catch(err => {
        console.error('加载时间段数据失败:', err);
        wx.showToast({ title: '加载失败', icon: 'none' });
        this.updateViewWithTimeSlots([], []);
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  /**
   * 根据API返回的时间段数据更新视图
   * @param {Array} todaySlots - 当天的时间段列表
   * @param {Array} tomorrowSlots - 次日的时间段列表
   */
  updateViewWithTimeSlots: function(todaySlots, tomorrowSlots) {
    const selectedDateObj = this.data.dateList.find(item => item.date === this.data.selectedDate);
    if (!selectedDateObj) return;

    const timeSlots = [...this.data.timeSlots];
    const now = new Date();
    const currentHour = now.getHours();
    
    const bookedToday = new Set(todaySlots.filter(s => !s.is_available).map(s => parseInt(s.hour)));
    const bookedTomorrow = new Set(tomorrowSlots.filter(s => !s.is_available).map(s => parseInt(s.hour)));

    // 如果是今天，并且当前小时被预订
    if (selectedDateObj.isToday && bookedToday.has(currentHour)) {
      let endHour = currentHour;
      // 寻找当前预定时间段的结束小时
      while (bookedToday.has(endHour + 1)) {
        endHour++;
      }
    }

    const updatedTimeSlots = timeSlots.map(slot => {
      let isBooked = false;
      let isPast = false;

      if (slot.isNextDay) {
        isBooked = bookedTomorrow.has(slot.hour);
      } else {
        isBooked = bookedToday.has(slot.hour);
        isPast = selectedDateObj.isToday && slot.hour < currentHour;
      }

      if (isBooked || isPast) {
        return { ...slot, status: 'booked' };
      } else {
        return { ...slot, status: 'available' };
      }
    });

    this.setData({
      timeSlots: updatedTimeSlots,
    });
  },

  // 加载场馆信息
  loadVenueInfo: async function (venueId) {
    this.setData({ loading: true });

    // 调用API获取场馆信息
    await api.venue.getVenueDetail(venueId)
      .then(res => {
        if (res.success) {
          let timeBasedPricing = [];
          if (res.data.time_based_pricing) {
            try {
              timeBasedPricing = JSON.parse(res.data.time_based_pricing);
            } catch (e) {
              console.error("Failed to parse time_based_pricing", e);
              timeBasedPricing = [];
            }
          }

          this.setData({
            venueInfo: res.data,
            hourlyPrice: res.data.hour_price,
            originalPrice: res.data.hour_price * 4,
            selectedStartTime:res.data.start_time,
            timeBasedPricing: timeBasedPricing,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.message || '获取场馆信息失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      })
      .catch(err => {
        console.error('获取场馆信息失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

  // 返回上一页
  onTapBack: function () {
    wx.navigateBack();
  },

  // 搜索输入
  onInputSearch: function (e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  // 选择日期
  onSelectDate: function (e) {
    const date = e.currentTarget.dataset.date;

    // 找到对应的时间选择器日期
    const dateObj = this.data.dateList.find(item => item.date === date);
    let timePickerDateIndex = 0;

    if (dateObj) {
      // 根据是否为今天/明天/后天来匹配时间选择器中的日期
      if (dateObj.isToday) {
        timePickerDateIndex = 0; // 今天
      } else {
        // 根据在dateList中的位置来确定是明天还是后天
        const index = this.data.dateList.findIndex(item => item.date === date);
        timePickerDateIndex = index;
      }
    }
    // 根据选择的日期更新小时选项
    this.updateHourListByDate(timePickerDateIndex);
    this.setData({
      selectedDate: date,
      // 同步更新时间选择器中的日期选择
      selectedTimePickerDate: this.data.timePickerDateList[timePickerDateIndex] || this.data.timePickerDateList[0],
    });

    // 根据选择的日期重新生成时间段并加载数据
    this.generateTimeSlots(dateObj.isToday);
  },

  // 选择套餐
  onSelectPackage: function (e) {
    if (this.data.selectedGroupBuy || this.data.selectedCoupon) {
      wx.showToast({
        title: '已使用优惠，无法选择套餐',
        icon: 'none'
      });
      return;
    }
    const packageId = e.currentTarget.dataset.package;

    // 查找选中的套餐信息
    const selectedPackageInfo = this.data.packageList.find(item => item.id === packageId);

    // 更新结束时间
    const startHour = parseInt(this.data.selectedStartTime.split(':')[0]);
    const startMinute = this.data.selectedStartTime.split(':')[1];
    const endHour = startHour + parseInt(selectedPackageInfo.hours);
    const endTime = (endHour % 24).toString().padStart(2, '0') + ':' + startMinute;

    // 检查套餐可用性
    if (!this.isItemAvailable(selectedPackageInfo, this.data.selectedDate, this.data.selectedStartTime, endTime)) {
      wx.showToast({
        title: '当前时间段不适用该套餐',
        icon: 'none'
      });
      return;
    }


    // 计算原价和优惠金额
    const hourlyPrice = this.data.hourlyPrice; // 每小时续单价格
    // 计算原价和优惠金额
    const originalPrice = hourlyPrice * parseInt(selectedPackageInfo.hours);
    // 从packagePrices中获取对应套餐的价格
    let price = selectedPackageInfo ? selectedPackageInfo.price : originalPrice;
    const discountAmount = originalPrice - price;

    console.log("selectedPackageInfo hours:",selectedPackageInfo.hours)
    this.setData({
      selectedPackage: packageId,
      orderHour:parseInt(selectedPackageInfo.hours),
      totalPrice: price,
      hourlyPrice: hourlyPrice,
      originalPrice: originalPrice,
      discountAmount: discountAmount.toFixed(1),
    });

    this.setData({
      selectedEndTime: endTime
    });
  },

  // 选择开始时间
  onSelectStartTime: function (e) {
    // 显示时间选择器模态框
    this.setData({
      isSelectingStartTime: true,
      showTimePickerModal: true
    });
  },

  // 选择结束时间
  onSelectEndTime: function (e) {
    // 显示时间选择器模态框
    this.setData({
      isSelectingStartTime: false,
      showTimePickerModal: true
    });
  },

  // 选择结束时间
  onSelectEndTime: function (e) {
    // 显示时间选择器模态框
    this.setData({
      isSelectingStartTime: false,
      showTimePickerModal: true
    });
  },

  // 选择时间选择器中的日期
  onSelectTimePickerDate: function (e) {
    const date = e.currentTarget.dataset.date;

    // 找到时间选择器日期在列表中的索引
    const index = this.data.timePickerDateList.findIndex(item => item === date);

    // 同步更新顶部日期选择
    let selectedDate = this.data.selectedDate;
    if (index >= 0 && index < this.data.dateList.length) {
      selectedDate = this.data.dateList[index].date;
    }

    this.setData({
      selectedTimePickerDate: date,
      selectedDate: selectedDate
    });

    // 根据选择的日期更新小时选项
    this.updateHourListByDate(index);
  },

  // 选择时间选择器中的小时
  onSelectTimePickerHour: function (e) {
    const hour = e.currentTarget.dataset.hour;
    this.setData({
      selectedTimePickerHour: hour
    });
  },

  // 选择时间选择器中的分钟
  onSelectTimePickerMinute: function (e) {
    const minute = e.currentTarget.dataset.minute;
    this.setData({
      selectedTimePickerMinute: minute
    });
  },

  /**
   * @description 根据开始和结束时间重新计算价格
   */
  recalculatePrice: function() {
    const startTime = this.data.selectedStartTime;
    const endTime = this.data.selectedEndTime;
    const timeBasedPricing = this.data.timeBasedPricing;
    const hourlyPrice = this.data.hourlyPrice;

    const price = priceCalculator.calculatePrice(startTime, endTime, timeBasedPricing, hourlyPrice);

    const start = startTime.split(':');
    const end = endTime.split(':');
    const startHour = parseInt(start[0]);
    const startMinute = parseInt(start[1]);
    const endHour = parseInt(end[0]);
    const endMinute = parseInt(end[1]);
    let duration = (endHour - startHour) + (endMinute - startMinute) / 60;
    if (duration < 0) {
      duration += 24;
    }
    console.log("recalculatePrice duration:",duration)
    this.setData({
      totalPrice: price.toFixed(2),
      orderHour: duration.toFixed(2),
      selectedPackage: 0, // 手动调整时间后，清除套餐选择
    });

    this.calculateTotalPrice();
  },

  // 确认时间选择
  onConfirmTimePicker: function () {
    // 格式化选中的时间
    const selectedTime = this.data.selectedTimePickerHour + ':' + this.data.selectedTimePickerMinute;

    // 根据当前是选择开始时间还是结束时间来更新对应的数据
    if (this.data.isSelectingStartTime) {
      this.setData({ selectedStartTime: selectedTime }, () => {
        // 开始时间变化后，同样需要重新计算总价
        this.recalculatePrice();
      });
    } else {
      // 更新结束时间
      this.setData({ selectedEndTime: selectedTime }, () => {
        this.recalculatePrice();
      });
    }

    // 关闭时间选择器模态框
    this.setData({
      showTimePickerModal: false
    });
  },

  // 查找最接近的套餐
  findClosestPackage: function(duration) {
    const packageHoursList = this.data.packageList.map(p => p.hours);
    if (packageHoursList.length === 0) {
      return 0; // 或者返回一个合理的默认值
    }
    // 找到与时长最接近的套餐
    return packageHoursList.reduce((prev, curr) => {
      return (Math.abs(curr - duration) < Math.abs(prev - duration) ? curr : prev);
    });
  },

  // 取消时间选择
  onCancelTimePicker: function () {
    // 关闭时间选择器模态框
    this.setData({
      showTimePickerModal: false
    });
  },

  // 预订 - 显示确认弹窗
  onTapBook: function () {
    // 确保余额支付金额是最新的
    this.calculateBalancePayment();
    
    const bookingData = {
      date: this.data.selectedDate,
      startTime: this.data.selectedStartTime,
      endTime: this.data.selectedEndTime,
      packageHours: this.data.orderHour,
      price: this.data.totalPrice,
      venueId: this.data.venueId,
      roomName: this.data.roomName
    };

    // 如果是续单，添加原订单信息
    if (this.data.isRenew && this.data.originalBookingId) {
      bookingData.isRenew = true;
      bookingData.originalBookingId = this.data.originalBookingId;
    }

    // 构建完整的日期时间字符串
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = parseInt(this.data.selectedDate.split('.')[1]);

    const startDateTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${this.data.selectedStartTime}`;
    const endDateTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${this.data.selectedEndTime}`;

    // 显示预定确认弹窗，并传递预定信息
    this.setData({
      showConfirmModal: true,
      confirmBookingInfo: {
        venueName: this.data.venueInfo.name || '',
        roomName: this.data.roomName || '',
        startDateTime: startDateTime,
        endDateTime: endDateTime,
        packageHours: this.data.orderHour,
        price: this.data.totalPrice,
        isRenew: this.data.isRenew,
        originalBookingId: this.data.originalBookingId
      }
    });
  },

  // 取消预定确认
  onCancelConfirm: function () {
    this.setData({
      showConfirmModal: false
    });
  },

  // 确认预定
  onConfirmBooking: function () {
    // 隐藏预定确认弹窗
    this.setData({
      showConfirmModal: false
    });

    // 获取选中的日期
    const dateParts = this.data.selectedDate.split('.');
    const year = new Date().getFullYear();
    const month = parseInt(dateParts[0]) - 1; // 月份从0开始
    const day = parseInt(dateParts[1]);

    // 获取选中的开始和结束时间
    const startTimeParts = this.data.selectedStartTime.split(':');
    const startHour = parseInt(startTimeParts[0]);
    const startMinute = parseInt(startTimeParts[1]);

    const endTimeParts = this.data.selectedEndTime.split(':');
    const endHour = parseInt(endTimeParts[0]);
    const endMinute = parseInt(endTimeParts[1]);

    // 创建日期对象
    const startDateTime = new Date(year, month, day, startHour, startMinute);
    const endDateTime = new Date(year, month, day, endHour, endMinute);

    // 如果结束时间小于开始时间，可能需要跨天处理
    if (endDateTime < startDateTime) {
      endDateTime.setDate(endDateTime.getDate() + 1);
    }
    
    // 转换为时间戳
    const startTimestamp = Math.floor(startDateTime.getTime() / 1000);
    const endTimestamp = Math.floor(endDateTime.getTime() / 1000);

    // 显示加载中
    wx.showLoading({
      title: '检查时间段...'
    });

    // 先检查时间段是否可用
    api.venue.checkTimeSlotAvailable(parseInt(this.data.venueId), startTimestamp, endTimestamp)
      .then(res => {
        if (res.success && res.data && res.data.available) {
          // 时间段可用，创建预订单并发起支付
          this.submitBooking();
        } else {
          // 时间段不可用，显示错误信息
          wx.hideLoading();
          wx.showModal({
            title: '预约失败',
            content: res.message || '该时间段不可预约，请选择其他时间',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('检查时间段失败:', err);
        wx.showModal({
          title: '预约失败',
          content: '检查时间段可用性失败，请稍后再试',
          showCancel: false
        });
      });
  },

  // 创建预约订单
  createBookingOrder: function(startTimestamp, endTimestamp) {
    // 构建预约数据
    const bookingData = {
      venue_id: parseInt(this.data.venueId),
      room_name: this.data.roomName,
      start_time: startTimestamp,
      end_time: endTimestamp,
      package_hours: parseInt(this.data.orderHour),
      total_amount: Math.round(this.data.totalPrice * 100), // 转换为分
      remark: ''
    };

    // 添加团购券ID（如果有）
    if (this.data.selectedGroupBuy && this.data.selectedGroupBuy.id) {
      bookingData.group_buy_id = this.data.selectedGroupBuy.id;
    }

    // 添加优惠券ID（如果有）
    if (this.data.selectedCoupon && this.data.selectedCoupon.id) {
      bookingData.coupon_id = this.data.selectedCoupon.id;
    }
    
    // 添加余额支付信息（如果选择使用余额）
    if (this.data.useBalance && this.data.balancePayAmount > 0) {
      bookingData.use_balance = 1;
      bookingData.balance_amount = Math.round(this.data.balancePayAmount * 100); // 转换为分
    } else {
      bookingData.use_balance = 0;
      bookingData.balance_amount = 0;
    }

    // 如果是续单，添加原订单ID
    if (this.data.isRenew && this.data.originalBookingId) {
      bookingData.is_renew = true;
      bookingData.original_booking_id = this.data.originalBookingId;
    }

    // 显示加载中
    wx.showLoading({
      title: '提交中...'
    });

    // 调用创建预约API
    api.order.createBooking(bookingData)
      .then(res => {
        wx.hideLoading();
        
        console.log('续单/预约API调用结果:', res);
        
        if (res.success) {
          // 预约成功
          wx.showToast({
            title: this.data.isRenew ? '续单成功' : '预约成功',
            icon: 'success',
            duration: 2000
          });
          
          // 确认返回数据结构中的订单ID字段
          let bookingId = null;
          
          // 检查可能的返回字段
          if (res.data && res.data.booking_id) {
            bookingId = res.data.booking_id;
          } else if (res.data && res.data.id) {
            bookingId = res.data.id;
          } else if (res.data && res.data.order_id) {
            bookingId = res.data.order_id;
          }
          
          console.log('获取到的订单ID:', bookingId);
          
          // 延迟跳转到订单详情页面
          setTimeout(() => {
            if (bookingId) {
              wx.redirectTo({
                url: `/pages/booking/detail?id=${bookingId}`,
                success: () => {
                  console.log('成功跳转到订单详情页');
                },
                fail: (err) => {
                  console.error('跳转失败:', err);
                  // 如果跳转失败，尝试返回预约列表页
                  wx.redirectTo({
                    url: '/pages/booking/index'
                  });
                }
              });
            } else {
              console.error('未获取到订单ID，跳转到预约列表页');
              // 如果没有订单ID，跳转到预约列表页
              wx.redirectTo({
                url: '/pages/booking/index'
              });
            }
          }, 1500);
        } else {
          // 预约失败
          console.error('续单/预约失败:', res.message);
          wx.showToast({
            title: res.message || '预约失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('续单/预约API调用异常:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 生成时间选择器的日期和小时选项
  generateTimePickerOptions: function () {
    // 生成日期选项 - 从当天开始的5天
    const now = new Date();
    const dateList = [];

    for (let i = 0; i < 5; i++) {
      const date = new Date(now);
      date.setDate(now.getDate() + i);

      // 格式化日期为MM月DD日格式
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');

      let dateText = month + '月' + day + '日';

      // 添加今天/明天/后天标记
      if (i === 0) dateText += '今天';
      else if (i === 1) dateText += '明天';
      else if (i === 2) dateText += '后天';

      dateList.push(dateText);
    }

    this.setData({
      timePickerDateList: dateList,
      selectedTimePickerDate: dateList[0]
    });

    // 初始化小时列表 - 默认使用当天的小时列表
    this.updateHourListByDate(0);
  },

  // 根据选择的日期更新小时选项
  updateHourListByDate: function (dateIndex) {
    const now = new Date();
    const hourList = [];

    // 如果是当天，从当前小时开始；否则从0点开始
    const startHour = dateIndex === 0 ? now.getHours() : 0;

    for (let i = startHour; i <= 23; i++) {
      hourList.push(i.toString().padStart(2, '0'));
    }

    this.setData({
      timePickerHourList: hourList,
      selectedTimePickerHour: hourList[0] || '00'
    });
  },

  // 加载套餐数据
  loadPackageData: function () {
    // 调用API获取套餐数据
    api.venue.getVenuePackages(this.data.venueId)
      .then(res => {
        if (res.success) {
          const packageList = res.data.list || [];
          let packagePrices = {};

          // 处理套餐数据
          packageList.forEach(pkg => {
            packagePrices[pkg.hours] = pkg.price;
          });

          this.setData({
            packageList: packageList,
            packagePrices: packagePrices
          });

          // 如果有套餐数据，设置默认选中的套餐
          if (packageList.length > 0) {
            this.setData({
              selectedPackage: packageList[0].id,
              orderHour:packageList[0].hours,
              totalPrice: packageList[0].price,
              originalPrice: packageList[0].original_price || this.data.hourlyPrice*packageList[0].hours,
              discountAmount: (packageList[0].original_price || packageList[0].price) - packageList[0].price
            });  
              // 计算总价
            this.calculateTotalPrice();
          }
        }
      })
      .catch(err => {
        console.error('获取套餐数据失败:', err);
      });
  },

  // 计算总价
  calculateTotalPrice: function () {
    const originalPrice = this.data.orderHour*this.data.hourlyPrice;
    // 从套餐价格中获取当前选中套餐的价格
    const selectedPackageItem = this.data.packageList.find(item=>item.id==this.data.selectedPackage);
    const packagePrice = selectedPackageItem ? selectedPackageItem.price : 0;
    let totalPrice = packagePrice?packagePrice:originalPrice;
    let discountAmount = 0;

    // 应用团购券折扣,不是套餐才能用团购券
    if (packagePrice==0&&this.data.selectedGroupBuy) {
      const groupBuy = this.data.selectedGroupBuy;
      
      // 判断团购券类型：如果有duration属性则为时长券，否则为金额券
      if (groupBuy.duration) {
        // 时长券：抵扣时长
        let groupBuyHours = 0;
        
        // 处理duration可能是数字或字符串的情况
        if (typeof groupBuy.duration === 'number') {
          groupBuyHours = groupBuy.duration;
        } else if (typeof groupBuy.duration === 'string') {
          groupBuyHours = parseInt(groupBuy.duration.match(/\d+/)) || 0;
        }
        discountAmount = this.data.hourlyPrice * groupBuyHours;
        totalPrice = Math.max(0, totalPrice - discountAmount);
      } else {
        // 金额券：直接抵扣金额
        const groupBuyAmount = groupBuy.amount || groupBuy.price || 0;
        totalPrice = Math.max(0, totalPrice - groupBuyAmount);
        discountAmount += groupBuyAmount;
        totalPrice = Math.max(0, totalPrice - discountAmount);
      }
    }

    // 应用优惠券折扣，不是套餐才能用优惠券
    if (packagePrice==0&&this.data.selectedCoupon) {
      // 检查优惠券使用条件
      const minConsume = this.data.selectedCoupon.min_consume || 0;

      if (totalPrice >= minConsume) {
        // 应用优惠券金额
        const couponAmount = this.data.selectedCoupon.amount || 0;
        totalPrice = Math.max(0, totalPrice - couponAmount);
        discountAmount += couponAmount;
      }
    }

    this.setData({
      totalPrice: totalPrice.toFixed(2),
      originalPrice: originalPrice.toFixed(2),
      discountAmount: discountAmount.toFixed(2)
    });
    
    // 更新余额支付金额
    this.calculateBalancePayment();
  },

  // 点击团购券，跳转到团购券页面
  onTapGroupon: function () {
    // 跳转到钱包页面并显示团购券标签页
    wx.navigateTo({
      url: '/pages/wallet/index?tabIndex=0'
    });
  },
  // 点击优惠券，跳转到优惠券页面
  onTapCoupon: function () {
    // 跳转到钱包页面并显示优惠券标签页
    wx.navigateTo({
      url: '/pages/wallet/index?tabIndex=1'
    });
  },

  // 点击充值，跳转到充值页面
  onTapRecharge: function () {
    // 点击充值按钮，跳转到账户充值页面
    wx.setStorageSync('couponTabIndex', 0);
    wx.reLaunch({
      url: '/pages/coupon/index',
      fail: function (res) {
        console.log('跳转失败', res);
      }
    });
  },

  // 点击时间段
  onTapTimeSlot: function(e) {
    const hour = e.currentTarget.dataset.hour;
    const status = e.currentTarget.dataset.status;
    
    // 如果该时间段已被占用，不可选择
    if (status === 'booked') {
      wx.showToast({
        title: '该时间段已被预约',
        icon: 'none'
      });
      return;
    }
    
    // 设置选中状态
    const timeSlots = this.data.timeSlots.map(slot => {
      if (slot.hour === hour) {
        return { ...slot, status: 'selected' };
      } else {
        return { ...slot, status: slot.status === 'booked' ? 'booked' : 'available' };
      }
    });
    
    // 计算结束时间 - 基于选中的小时和套餐时长
    const startHour = parseInt(hour);
    const packageHours = parseInt(this.data.orderHour);
    const endHour = startHour + packageHours;
    
    // 检查是否有预订冲突
    let hasConflict = false;
    for (let i = startHour; i < endHour; i++) {
      const hourToCheck = i % 24; // 处理跨天的情况
      const slotToCheck = this.data.timeSlots.find(slot => parseInt(slot.hour) === hourToCheck);
      if (slotToCheck && slotToCheck.status === 'booked') {
        hasConflict = true;
        break;
      }
    }
    
    if (hasConflict) {
      wx.showToast({
        title: '所选时间段内有已预约时段',
        icon: 'none'
      });
      return;
    }
    
    // 获取选中的日期
    const dateParts = this.data.selectedDate.split('.');
    const year = new Date().getFullYear();
    const month = parseInt(dateParts[0]) - 1; // 月份从0开始
    const day = parseInt(dateParts[1]);
    
    // 创建开始和结束的日期时间对象
    const startDateTime = new Date(year, month, day, startHour, 0);
    const endDateTime = new Date(year, month, day, endHour, 0);
    
    // 如果结束时间小于开始时间，可能需要跨天处理
    if (endDateTime < startDateTime) {
      endDateTime.setDate(endDateTime.getDate() + 1);
    }
    
    // 转换为时间戳
    const startTimestamp = Math.floor(startDateTime.getTime() / 1000);
    const endTimestamp = Math.floor(endDateTime.getTime() / 1000);
    
    // 调用后端API检查时间段是否可预约
    wx.showLoading({
      title: '检查时间段...'
    });
    
    api.venue.checkTimeSlotAvailable(parseInt(this.data.venueId), startTimestamp, endTimestamp)
      .then(res => {
        wx.hideLoading();
        if (res.success && res.data && res.data.available) {
          // 时间段可用，更新UI
          this.setData({
            timeSlots: timeSlots,
            selectedStartTime: hour + ':00',
            selectedEndTime: (endHour % 24) + ':00'
          });
          
          // 添加震动反馈
          wx.vibrateShort({
            type: 'medium'
          });
          
          // 显示选中成功的提示
          wx.showToast({
            title: '已选择 ' + hour + ':00 开始',
            icon: 'success'
          });
        } else {
          // 时间段不可用，显示错误信息
          wx.showModal({
            title: '提示',
            content: res.message || '该时间段不可预约，请选择其他时间',
            showCancel: false
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('检查时间段失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      });
  },

  // 加载账户信息
  loadAccountInfo: function() {
    wx.showLoading({ title: '加载账户信息...' });
    
    api.user.getAccountInfo()
      .then(res => {
        if (res && res.success && res.data) {
          // 格式化余额，确保显示两位小数
          const balance = parseFloat(res.data.balance || 0).toFixed(2);
          
          this.setData({
            accountInfo: {
              ...res.data,
              balance: balance
            }
          });
          
          // 计算可用余额支付金额
          this.calculateBalancePayment();
        }
      })
      .catch(err => {
        console.error('获取账户信息失败:', err);
      })
      .finally(() => {
        wx.hideLoading();
      });
  },
  
  // 计算余额支付金额
  calculateBalancePayment: function() {
    if (!this.data.accountInfo) return;
    
    const totalPrice = parseFloat(this.data.totalPrice);
    const balance = parseFloat(this.data.accountInfo.balance);
    
    // 如果余额足够支付全部
    if (balance >= totalPrice) {
      this.setData({
        balancePayAmount: totalPrice,
        remainingPayAmount: 0
      });
    } else {
      // 如果余额不足，部分使用余额
      this.setData({
        balancePayAmount: balance,
        remainingPayAmount: totalPrice - balance
      });
    }
  },
  
  // 切换是否使用余额支付
  toggleUseBalance: function() {
    const useBalance = !this.data.useBalance;
    
    this.setData({
      useBalance: useBalance
    });
    
    // 重新计算余额支付金额
    this.calculateBalancePayment();
  },

  // 在submitBooking方法中先创建临时订单，获取支付参数，然后发起支付
  submitBooking: function() {
    // 隐藏确认弹窗
    this.setData({
      showConfirmModal: false
    });
    
    // 显示加载中
    wx.showLoading({
      title: '处理中...'
    });
    
    // 获取当前时间
    const now = new Date();
    const year = now.getFullYear();
    const month = now.getMonth() + 1;
    const day = parseInt(this.data.selectedDate.split('.')[1]);
    
    // 解析开始和结束时间字符串为时间戳
    const startTimeStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${this.data.selectedStartTime}`;
    const endTimeStr = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${this.data.selectedEndTime}`;
    
    const startDate = new Date(startTimeStr);
    const endDate = new Date(endTimeStr);
    
    // 转换为时间戳（秒）
    const startTimestamp = Math.floor(startDate.getTime() / 1000);
    const endTimestamp = Math.floor(endDate.getTime() / 1000);
    
    // 计算支付金额
    const useBalance = this.data.useBalance;
    const totalPriceInCents = Math.round(this.data.totalPrice * 100); // 转换为分
    
    // 提交预约订单
    const bookingData = {
      venue_id: parseInt(this.data.venueId),
      start_time: startTimestamp,
      end_time: endTimestamp,
      total_amount: totalPriceInCents,
      use_balance: useBalance ? 1 : 0,
      balance_amount: Math.round(this.data.balancePayAmount * 100),
      remark: ''
    };
    
    // 如果选择了优惠券，添加优惠券ID
    if (this.data.couponId) {
      bookingData.coupon_id = this.data.couponId;
    }
    
    // 如果选择了团购券，添加团购券ID
    if (this.data.groupBuyId) {
      bookingData.group_buy_id = parseInt(this.data.groupBuyId);
    }
    
    // 根据是否续单选择不同的API接口
    const preOrderMethod = this.data.isRenew ? api.order.createRenewPreOrder : api.order.createPreOrder;
    
    // 如果是续单，添加原订单ID
    if (this.data.isRenew && this.data.originalBookingId) {
      bookingData.original_booking_id = parseInt(this.data.originalBookingId);
    }
    
    // 调用创建预订单API - 预订单只是为了获取支付参数，不会立即创建正式订单
    preOrderMethod(bookingData)
      .then(res => {
        console.log('预订单创建结果:', res);
        
        if (res.success && res.data) {
          // 判断是否需要支付
          if (res.data.need_pay === false) {
            // 无需支付（例如全部使用余额），直接创建正式订单
            this.createFinalOrder(res.data.pre_order_id);
          } else if (res.data.pay_params) {
            // 需要支付，调起微信支付
            const payParams = res.data.pay_params;
            
            // 保存预订单ID，支付成功后使用
            this.setData({
              preOrderId: res.data.pre_order_id
            });
            
            wx.hideLoading();
            
            // 调起微信支付
            wx.requestPayment({
              timeStamp: payParams.timeStamp,
              nonceStr: payParams.nonceStr,
              package: payParams.package,
              signType: payParams.signType,
              paySign: payParams.paySign,
              success: (payRes) => {
                console.log('支付成功:', payRes);
                // 支付成功，创建正式订单
                this.createFinalOrder(res.data.pre_order_id);
              },
              fail: (err) => {
                console.error('支付失败:', err);
                wx.showModal({
                  title: '支付失败',
                  content: '您的订单支付未完成，请重新尝试',
                  showCancel: true,
                  cancelText: '取消',
                  confirmText: '重试',
                  success: (modalRes) => {
                    if (modalRes.confirm) {
                      // 用户选择重试支付
                      this.retryPayment(res.data.pre_order_id);
                    } else {
                      // 用户取消，返回上一页
                      wx.navigateBack();
                    }
                  }
                });
              }
            });
          } else {
            wx.hideLoading();
            wx.showToast({
              title: '创建订单失败：支付参数错误',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.hideLoading();
          wx.showToast({
            title: res.message || '创建订单失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('创建预订单异常:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      });
  },
  
  // 重试支付
  retryPayment: function(preOrderId) {
    wx.showLoading({ title: '加载中...' });
    
    // 获取支付参数
    api.order.getPayParams({ pre_order_id: preOrderId })
      .then(res => {
        wx.hideLoading();
        if (res.success && res.data && res.data.pay_params) {
          const payParams = res.data.pay_params;
          
          // 调起微信支付
          wx.requestPayment({
            timeStamp: payParams.timeStamp,
            nonceStr: payParams.nonceStr,
            package: payParams.package,
            signType: payParams.signType,
            paySign: payParams.paySign,
            success: (payRes) => {
              console.log('重试支付成功:', payRes);
              // 支付成功，创建正式订单
              this.createFinalOrder(preOrderId);
            },
            fail: (err) => {
              console.error('重试支付失败:', err);
              wx.showModal({
                title: '支付失败',
                content: '您的订单支付未完成',
                showCancel: false,
                confirmText: '知道了'
              });
            }
          });
        } else {
          wx.showToast({
            title: res.message || '获取支付参数失败',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('获取支付参数失败:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        });
      });
  },
  
  // 创建正式订单
  createFinalOrder: function(preOrderId) {
    wx.showLoading({ title: '确认订单中...' });
    
    const confirmMethod = this.data.isRenew ? api.order.confirmRenewOrder : api.order.confirmOrder;
    
    confirmMethod({ pre_order_id: preOrderId })
      .then(res => {
        wx.hideLoading();
        
        console.log('正式订单创建结果:', res);
        
        if (res.success) {
          // 预约成功
          wx.showToast({
            title: this.data.isRenew ? '续单成功' : '预约成功',
            icon: 'success',
            duration: 2000
          });
          
          // 确认返回数据结构中的订单ID字段
          let bookingId = null;
          
          // 检查可能的返回字段
          if (res.data && res.data.booking_id) {
            bookingId = res.data.booking_id;
          } else if (res.data && res.data.id) {
            bookingId = res.data.id;
          } else if (res.data && res.data.order_id) {
            bookingId = res.data.order_id;
          }
          
          console.log('获取到的订单ID:', bookingId);
          
          // 延迟跳转到订单详情页面
          setTimeout(() => {
            if (bookingId) {
              wx.redirectTo({
                url: `/pages/booking/detail?id=${bookingId}`,
                success: () => {
                  console.log('成功跳转到订单详情页');
                },
                fail: (err) => {
                  console.error('跳转失败:', err);
                  // 如果跳转失败，尝试返回预约列表页
                  wx.redirectTo({
                    url: '/pages/booking/index'
                  });
                }
              });
            } else {
              console.error('未获取到订单ID，跳转到预约列表页');
              // 如果没有订单ID，跳转到预约列表页
              wx.redirectTo({
                url: '/pages/booking/index'
              });
            }
          }, 1500);
        } else {
          // 创建失败
          console.error('创建正式订单失败:', res.message);
          wx.showToast({
            title: res.message || '创建订单失败',
            icon: 'none',
            duration: 2000
          });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('创建正式订单异常:', err);
        wx.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none',
          duration: 2000
        });
      });
  },

  // 加载可用优惠券
  loadAvailableCoupons: function() {
    const amount = this.data.totalPrice || 0;
    
    wx.showLoading({
      title: '加载优惠券...',
    });
    
    api.coupon.getAvailableCoupons({ amount: amount })
      .then(res => {
        if (res.success) {
          // 处理优惠券数据
          const now = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
          const coupons = res.data.map(item => {
            // 检查优惠券是否过期
            const isExpired = now > item.valid_until;
            return {
              ...item,
              value_text: item.type === 1 ? `¥${item.value}` : `${item.value}折`,
              is_expired: isExpired // 添加过期标志
            };
          });
          
          // 过滤掉已过期的优惠券
          const validCoupons = coupons.filter(coupon => !coupon.is_expired);
          
          this.setData({
            availableCoupons: validCoupons,
            hasCoupons: validCoupons.length > 0
          });
        } else {
          this.setData({
            availableCoupons: [],
            hasCoupons: false
          });
        }
      })
      .catch(err => {
        console.error('获取优惠券失败:', err);
        this.setData({
          availableCoupons: [],
          hasCoupons: false
        });
      })
      .finally(() => {
        wx.hideLoading();
      });
  },

  // 选择优惠券
  onSelectCoupon: function(e) {
    const couponId = e.currentTarget.dataset.id;
    const coupon = this.data.availableCoupons.find(item => item.id === couponId);
    
    if (coupon) {
      if (coupon.is_expired) {
        wx.showToast({
          title: '该优惠券已过期',
          icon: 'none'
        });
        return;
      }
      
      let discountAmount = 0;
      
      // 根据优惠券类型计算折扣金额
      if (coupon.type === 1) { // 满减券
        discountAmount = parseFloat(coupon.value);
      } else if (coupon.type === 2) { // 折扣券
        const discount = parseFloat(coupon.value) / 10;
        discountAmount = this.data.totalPrice * (1 - discount);
      } else if (coupon.type === 3) { // 无门槛券
        discountAmount = parseFloat(coupon.value);
      }
      
      // 最多优惠到0元
      const finalPrice = Math.max(0, this.data.totalPrice - discountAmount);
      
      this.setData({
        selectedCoupon: coupon,
        couponDiscount: discountAmount.toFixed(2),
        actualPrice: finalPrice.toFixed(2)
      });
      
      // 更新余额支付金额
      this.calculateBalancePayment();
      
      // 关闭优惠券选择模态框
      this.toggleCouponModal();
    }
  },
  
  // 切换优惠券选择模态框
  toggleCouponModal: function() {
    const showCouponModal = !this.data.showCouponModal;
    
    if (showCouponModal) {
      // 打开模态框时加载可用优惠券
      this.loadAvailableCoupons();
    }
    
    this.setData({
      showCouponModal: showCouponModal
    });
  },
});

